﻿using System.Reflection;

namespace 反射调用方法
{
    internal class Program
    {
        static void Main(string[] args)
        {

            Assembly assembly = Assembly.GetExecutingAssembly();

            Console.WriteLine(assembly.FullName);


            // 使用反射创建对象实例
            // 获取类型信息  
            Type type = Type.GetType("反射调用方法.MyClass");
            // 创建对象实例  
            object instance = Activator.CreateInstance(type);
            // 使用实例  
            (instance as MyClass).Show();
            MethodInfo methodInfo = type.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
            // 反射调用公有的方法
            int sum = (int)methodInfo.Invoke(instance,new object[]{ 4,5});
            Console.WriteLine(sum);

            // 创建类的实例，调用私有方法
            type = Type.GetType("反射调用方法.Person");
            object[] parameters = { "yejing", 35 }; // 传递给构造函数的参数列表  
            instance = Activator.CreateInstance(type, parameters);
            (instance as Person).Show();
            // 获取 MyPrivateMethod 的 MethodInfo 对象  
            methodInfo = type.GetMethod("Gongzi", BindingFlags.NonPublic | BindingFlags.Instance);
            // 调用方法  
            methodInfo.Invoke(instance, null);

        }
    }


    internal class MyClass
    {
        public MyClass() { }


        public void Show()
        {
            Console.WriteLine("MyClass");
        }

        public int Add(int x,int y)
        {
            return x + y;
        }

    }


    internal class Person
    {
        private string _name;
        private int _age;

        public Person() { }
        public Person(string name, int age)
        {
            _name = name;   
            _age = age;
        }

        public void Show()
        {
            Console.WriteLine($"name:{_name},age:{_age}");
        }

        private void Gongzi()
        {
            Console.WriteLine($"name:{_name},age:{_age},工资保密");
        }


    }


}
